package com.szgr.baoyin.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.activity.LoginActivity;
import com.szgr.baoyin.interfaces.PersonalInterface;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的
 * Created by Jimbo on 2015/9/16.
 */
public class PersonalFragment extends Fragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener ,PersonalSaveFragment.PersonalInterface {
    private List<Fragment> fragments;
    private Dialog dialog;
    private PersonalInterface pi;
    private TextView tv_name;
    private Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    HashMap map = (HashMap) msg.obj;
                    MyApplication.getmInstance().setUsericon((String)map.get("user_icon"));
                    MyApplication.getmInstance().setUsername((String) map.get("user_name"));
                    tv_name.setText((String)map.get("user_name"));
                    MyTool.showPicture(getActivity(),img_icon,(String)map.get("user_icon"));

                    break;
            }
        }
    };
    private RadioButton rb_save;
    private ImageView img_icon;
    private PersonalReceiver personalReceiver;

    public PersonalFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_personal,container,false);
        initView(ret);
        return ret;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!MyApplication.getmInstance().isLogin()) {
            if(dialog != null && !dialog.isShowing() && !this.isHidden()) {
                dialog.show();
            }
        }else{
            if(MyApplication.getmInstance().getUsericon() == null) {
                getUserMessage();
            }else{
                tv_name.setText(MyApplication.getmInstance().getUsername());
                MyTool.showPicture(getActivity(),img_icon,MyApplication.getmInstance().getUsericon());
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserMessage() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_MY_MESSAGE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                JSONObject member_info = datas.getJSONObject("member_info");
                                String user_name = member_info.getString("user_name");
                                String user_icon = member_info.getString("avator");
                                HashMap<String,String> map = new HashMap<>();
                                map.put("user_name",user_name);
                                map.put("user_icon",user_icon);
                                mhandler.obtainMessage(Constant.REQUEST_SUCCESS,map).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void initView(View ret) {
        pi = (PersonalInterface) getActivity();
        fragments = new ArrayList<>();
        addFragments();
        RadioGroup rg_personal = (RadioGroup) ret.findViewById(R.id.personal_radio_group);
        rb_save = (RadioButton) ret.findViewById(R.id.personal_save);
        rg_personal.setOnCheckedChangeListener(this);
        ((RadioButton)rg_personal.getChildAt(0)).setChecked(true);
        img_icon = (ImageView) ret.findViewById(R.id.my_icon);
        tv_name = (TextView) ret.findViewById(R.id.personal_name);
        initDialog();

        personalReceiver = new PersonalReceiver();
        IntentFilter filter = new IntentFilter("MyReceiver_Action");
        getActivity().registerReceiver(personalReceiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
//        getActivity().unregisterReceiver(personalReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(personalReceiver);
    }

    private void initDialog() {
        dialog = DialogUtils.showCustomerDialog(getActivity(),
                "您还未登录，请登录注册后再操作","立即登录注册","稍后注册",
                this,this);
        dialog.setCancelable(false);
    }

    private void addFragments() {
        fragments.add(new PersonalOrderFragment());
        fragments.add(new PersonalMessageFragment());
        fragments.add(new PersonalSaveFragment());
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.personal_order:
                replaceFragment(new PersonalOrderFragment());
                break;
            case R.id.personal_message:
                replaceFragment(new PersonalMessageFragment());
                break;
            case R.id.personal_save:
                PersonalSaveFragment fragment = new PersonalSaveFragment();
                fragment.setListener(this);
                replaceFragment(fragment);
                break;
        }
    }

    private void replaceFragment(Fragment fragment) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if(!fragments.contains(fragment)){
            fragments.add(fragment);
            transaction.add(R.id.personal_container,fragment);
        }
//        transaction.replace(R.id.personal_container,fragment);
        for (Fragment f : fragments) {
            transaction.hide(f);
        }
        transaction.show(fragment);
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.protect_buy_now:
                dialog.dismiss();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.protect_buy_next:
                dialog.dismiss();
                pi.back();
                break;
        }
    }

    @Override
    public void back(int num) {
        rb_save.setText("我的收藏" + "(" + num + ")");
    }

    public class PersonalReceiver extends BroadcastReceiver {
        public PersonalReceiver() {

        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if(!MyApplication.getmInstance().isLogin()) {
                if(dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }else{
                if(MyApplication.getmInstance().getUsericon() == null) {
                    getUserMessage();
                }else{
                    tv_name.setText(MyApplication.getmInstance().getUsername());
                    MyTool.showPicture(getActivity(),img_icon,MyApplication.getmInstance().getUsericon());
                }
            }
        }
    }
}
